package com.firefighting.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.firefighting.entity.Task;
import com.firefighting.entity.User;
import com.firefighting.service.MaintenanceTaskService;
import com.firefighting.service.MaintenanceplanContentService;
import com.firefighting.service.TaskItemService;
import com.firefighting.service.UserBasicInfoService;

@Controller
@RequestMapping("MaintenanceTask")
public class MaintenanceTaskController
{
	@Autowired
	private MaintenanceTaskService maintenanceTaskService;
	
	@Autowired
	private TaskItemService taskItemService;
	@Autowired
	private UserBasicInfoService userbasic;
	
	@Autowired
	private MaintenanceplanContentService maintenanceplanContentService;
	
	/**
	 * @author zhyan
	 * @function 展示维保任务列表
	 * @date 2018.6.25
	 * @author Hanjd 维护
	 */
	@RequestMapping("taskList")
	private String getMaintenanceTaskList(HttpServletRequest request, Model model) throws JsonGenerationException, JsonMappingException, IOException
	{
		ObjectMapper objectMapper = new ObjectMapper();
		@SuppressWarnings("rawtypes")
		List<HashMap> result =  new ArrayList<>();
		
		//获取登陆用户
		User user =	(User)request.getSession().getAttribute("currentUser");
		//根据用户获取用户角色
		int roleId = user.getRoleid();
		//获取用户所属企业id
		//System.out.println("user.getUsername()---"+user.getUsername());
		Integer enterId = userbasic.getEnterId(user.getUsername());
		String account = user.getUsername();
		String addJsp = null;
		//System.out.println("roleId---"+roleId);
		switch(roleId){
			case 1://企业负责人
				result = maintenanceTaskService.queryEnterMaintenanceTaskList(enterId);
				addJsp = "maintenanceTask/task";
				break;
			case 2://项目负责人
				result = maintenanceTaskService.queryExactMaintenanceTaskList(account);
				//System.out.println(account+"项目负责人"+result);
				addJsp = "maintenanceTask/task";
				break;
			case 11://平台管理员
				result = maintenanceTaskService.queryMaintenanceTaskList();
				addJsp = "maintenanceTask/task";
				break;
		}
		
		model.addAttribute("content", objectMapper.writeValueAsString(result));
		//System.out.println(result);
		return addJsp;
	}
	/**
	 * @author Liuxc
	 * 总队查看单个合同的维保任务列表
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonGenerationException 
	 * */
	@RequestMapping("getTaskListOfContract")
	public String getTaskListOfContract(HttpServletRequest request ,Model model) throws JsonGenerationException, JsonMappingException, IOException{
		ObjectMapper objectMapper = new ObjectMapper();
		String contactId = request.getParameter("contractId");
		int id = Integer.parseInt(contactId);
		@SuppressWarnings("rawtypes")
		List<HashMap> taskList =  new ArrayList<>();
		taskList = maintenanceTaskService.getTaskListByContracrId(id);
		model.addAttribute("taskList", objectMapper.writeValueAsString(taskList));
		return "maintenanceProject/viewTask";
		
	}
	
	
	
	/**
	 * @author zhyan
	 * @function 维保任务的详细内容
	 * @date 2018.6.25
	 */
	@RequestMapping("taskDetail")
	private String getMaintenanceTaskDetail(HttpServletRequest request, Model model) throws JsonGenerationException, JsonMappingException, IOException
	{
		ObjectMapper objectMapper = new ObjectMapper();
		int id = Integer.parseInt(request.getParameter("id"));
		
		@SuppressWarnings("rawtypes")
		HashMap detailContent = maintenanceTaskService.queryMaintenanceTaskById(id);
		model.addAttribute("detailContent", detailContent);
		
		@SuppressWarnings("rawtypes")
		List<HashMap> result = taskItemService.queryTaskItemListByTaskId(id);
		model.addAttribute("content", objectMapper.writeValueAsString(result));
		
		return "maintenanceTask/check";
	}
	
	/**
	 * @author zhyan
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonGenerationException 
	 * @function 根据任务内容id查询该任务内容的详细信息
	 * @date 2018.6.25
	 */
	@RequestMapping("itemDetail")
	private String getTaskItemDetail(HttpServletRequest request, Model model) throws JsonGenerationException, JsonMappingException, IOException
	{
		ObjectMapper objectMapper = new ObjectMapper();
		int id = Integer.parseInt(request.getParameter("id"));
		
		@SuppressWarnings("rawtypes")
		HashMap result = taskItemService.queryTaskItemInfo(id);
		
		@SuppressWarnings("rawtypes")
		List<HashMap> list = new ArrayList<HashMap>();
		
		list.add(result);
		model.addAttribute("result", result);
		model.addAttribute("content", objectMapper.writeValueAsString(list));
		
		return "maintenanceTask/taskInfo";
	}
	
	/**
	 * @author zhyan
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonGenerationException 
	 * @function 更新审核状态和审核意见
	 * @date 2018.6.25
	 */
	@RequestMapping("saveUpdate")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
	@ResponseBody 
	private String saveCheckAdvice(HttpServletRequest request, Model model) throws JsonGenerationException, JsonMappingException, IOException
	{
		int id = Integer.parseInt(request.getParameter("id"));
		String status = request.getParameter("status");
		String checkOpinion = request.getParameter("checkOpinion");
		Map<String,Object> returnContent = new HashMap<String,Object>();
		User user = (User) request.getSession().getAttribute("currentUser");
		String auditor = user.getUsername();
		ObjectMapper objectMapper = new ObjectMapper();
		Task task = maintenanceTaskService.queryTaskById(id);
		//审核通过之后不能在审核
		if(task.getStatus().equals("审核通过"))
		{
			returnContent.put("content", "checked");
			//return returnContent;
			//return JSONObject.toJSONString(returnContent);
			return objectMapper.writeValueAsString(returnContent);
		}
		
		//若审核状态不是待审核，不能保存
		if(!task.getStatus().equals("待审核"))
		{
			returnContent.put("content", "status");
			return JSONObject.toJSONString(returnContent);
			//return returnContent;
		}
		
		/**
		 * 查看该任务中所有任务项的状态：只有在所有任务项是‘已执行’状态的时候，才可以进行保存
		 */
		List<String> result = maintenanceplanContentService.selectFinishedStateByPlanIdAndContentIdList(task.getMaintenanceplanId(), 
				taskItemService.queryMaintenanceContentIdListByTaskId(id));
		for(String element : result)
		{
			//如果存在状态不是“已执行”的任务项，提示任务项还没有被全部执行，无法保存
			if(!element.equals("已执行"))
			{
				returnContent.put("content", "unexecuted");
				return JSONObject.toJSONString(returnContent);
				//return returnContent;
			}
		}
		
		//任务中的所有任务项都是“已执行”，则审核通过后将其状态修改为“已完成”
		int number = maintenanceTaskService.updateCheckResultAndOpinionById(id, status, checkOpinion,auditor);//更新任务的状态为通过
		//更新任务中所有任务项的状态为“已完成”
		int update = maintenanceplanContentService.updateFinishedStateByPlanIdAndContentIdList("已完成", task.getMaintenanceplanId(), 
				taskItemService.queryMaintenanceContentIdListByTaskId(id));
		
		if(number > 0 && update > 0)
		{
			returnContent.put("content", "true");//更新成功
		}
		else
		{
			returnContent.put("content", "false");//更新失败
		}
		
		return JSONObject.toJSONString(returnContent);
		//return returnContent;
	}
}